package com.example.mytips.utils;

import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class ReadFileUtil {

    /// 读取VirtualFile的内容
    /// VirtualFile fileByPath = LocalFileSystem.getInstance().findFileByPath("文件绝对路径");
    public static List<String> read(VirtualFile selectedFile) {
        // 获取当前选中的文件

        List<String> list = new ArrayList<>();
        if (selectedFile != null) {
            try {
                // 创建BufferedReader来读取文件内容
                BufferedReader br = new BufferedReader(new InputStreamReader(selectedFile.getInputStream()));
                String currentLine;
                while ((currentLine = br.readLine()) != null) {
                    list.add(currentLine);
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return list;
    }

    ///把数组写入到VirtualFile
    public static boolean write(VirtualFile selectedFile, List<String> lines) {

        if (selectedFile != null) {
            // 将List<String>转换为字符串，并添加换行符
            String content = String.join(System.lineSeparator(), lines);
            // 将字符串转换为字节数组
            byte[] bytes = content.getBytes(StandardCharsets.UTF_8);

            // 覆盖写入内容到文件
            try {
                selectedFile.setBinaryContent(bytes);

            } catch (IOException ex) {
                ex.printStackTrace();
                return false;
            }

            return true;
        }

        return false;
    }
}
